package com.adtec.yxdemo.datascraping.service;


import cn.hutool.json.JSONArray;
import com.adtec.yxdemo.datascraping.entity.bo.Detils;
import com.adtec.yxdemo.datascraping.entity.po.YxDetails;
import com.adtec.yxdemo.datascraping.entity.po.YxOrderDetails;
import com.adtec.yxdemo.datascraping.entity.po.YxPayInfo;
import com.adtec.yxdemo.datascraping.entity.po.YxPayTrack;
import com.adtec.yxdemo.datascraping.service.base.*;
import com.adtec.yxdemo.mockLogin.entity.po.YxAccountInfo;
import com.adtec.yxdemo.utils.DataUtil;
import com.adtec.yxdemo.utils.LoginUtil;
import com.adtec.yxdemo.utils.YxUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;

import io.jboot.db.model.Columns;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.util.Date;
import java.util.List;

public class DataScrapingService {
    @Inject
    BaseYxPayInfoService baseYxPayInfoService;
    @Inject
    BaseAccountService baseAccountService;
    @Inject
    BaseYxOrderDetailsService baseYxOrderDetailsService;
    @Inject
    BaseYxPayTrackService baseYxPayTrackService;
    @Inject
    BaseYxDetailsService baseYxDetailsService;

    /**
     * 爬取支付订单集合并遍历数据写入数据库
     */
    public void getYxPayInfo(YxAccountInfo yxAccountInfo) {
        JSONArray payInfoList = getList(yxAccountInfo);
        for (int i = 0; i < payInfoList.size(); i++) {
            YxPayInfo yxPayInfo = JSONObject.parseObject(payInfoList.get(i).toString(), YxPayInfo.class);
            if (yxPayInfo.getAuditStatus().equals("2")) {
                yxPayInfo.setAuditStatus("审核通过");
            } else {
                yxPayInfo.setAuditStatus("审核未通过");
            }
            yxPayInfo.setAddTime(YxUtil.dataConversion(yxPayInfo.getAddTime()));
            yxPayInfo.setPayStatus(YxUtil.getPayStutas(yxPayInfo.getPayStatus()));
            yxPayInfo.setDatePulltime(new Date());
            yxPayInfo.setDatePulluser(yxAccountInfo.getAccountUsername());
            YxPayInfo info = baseYxPayInfoService.findFirstByColumns(Columns.create("pay_order_code", yxPayInfo.getPayOrderCode()));
            if (info == null) {
                baseYxPayInfoService.save(yxPayInfo);
            } else {
                baseYxPayInfoService.update(yxPayInfo);
            }
        }
    }

    /**
     * 循环取用户爬取所有信息
     */
    public void getInfos() {
//        用户集合
        List<YxAccountInfo> accountInfoList = baseAccountService.findListByColumns(Columns.create("login_status", "1"));
        int i = 0;
        while (i < accountInfoList.size()) {
            YxAccountInfo yxAccountInfo = accountInfoList.get(i);//第start个用户
            getYxPayInfo(yxAccountInfo);
            ++i;
        }
    }

    /**
     * 循环取用户爬取所有信息
     */
    public void getDetails() {
//        用户集合
        List<YxAccountInfo> accountInfoList = baseAccountService.findListByColumns(Columns.create("login_status", "1"));
        int i = 0;
        while (i < accountInfoList.size()) {
            YxAccountInfo yxAccountInfo = accountInfoList.get(i);//第start个用户
            getDetails(yxAccountInfo);
            ++i;
        }
    }

    /**
     * 循环取用户爬取所有信息
     */
    public void getPayTrack() {
//        用户集合
        List<YxAccountInfo> accountInfoList = baseAccountService.findListByColumns(Columns.create("login_status", "1"));
        int i = 0;
        while (i < accountInfoList.size()) {
            YxAccountInfo yxAccountInfo = accountInfoList.get(i);//第start个用户
            getTrack(yxAccountInfo);
            ++i;
        }
    }

    /**
     * 爬取支付详情数据写入数据库
     */
    public void getDetails(YxAccountInfo yxAccountInfo) {
        JSONArray yxInfoLists = getList(yxAccountInfo);
        for (int i = 0; i < yxInfoLists.size(); i++) {
            YxPayInfo yxPayInfo = JSONObject.parseObject(yxInfoLists.get(i).toString(), YxPayInfo.class);
            String body = DataUtil.getOrderDetail1(yxAccountInfo, yxPayInfo.getPayOrderCode());
            YxOrderDetails yxOrderDetails = getYxDetails(body, yxPayInfo.getPayOrderCode(), yxAccountInfo);
            YxOrderDetails order = baseYxOrderDetailsService.findFirstByColumns(Columns.create("pay_order_code", yxPayInfo.getPayOrderCode()));
            if (order == null) {
                baseYxOrderDetailsService.save(yxOrderDetails);
            } else {
                baseYxOrderDetailsService.update(yxOrderDetails);
            }
            JSONArray orderDetailsList = DataUtil.getOrderDetails(yxAccountInfo, yxPayInfo.getPayOrderCode());
            for (int y = 0; y < orderDetailsList.size(); y++) {
                String str = orderDetailsList.get(y).toString();
                YxDetails yxDetails = JSONObject.parseObject(str, YxDetails.class);
                if (yxDetails.getStorageTag().equals("1")) {
                    yxDetails.setStorageTag("收货");
                } else {
                    yxDetails.setStorageTag("退货");
                }
                Detils detils = JSONObject.parseObject(str, Detils.class);
                YxDetails yxDetail = getYxDetails(detils, yxDetails);
                yxDetail.setPayOrderCode(yxPayInfo.getPayOrderCode());
                YxDetails tail = baseYxDetailsService.findFirstByColumns(Columns.create("invoice_id", yxDetail.getInvoiceId()));
                if (tail == null) {
                    baseYxDetailsService.save(yxDetail);
                } else {
                    baseYxDetailsService.update(yxDetail);
                }
            }
        }
    }

    /**
     * 爬取支付跟踪跟踪信息并写入数据库
     */
    public void getTrack(YxAccountInfo yxAccountInfo) {
        JSONArray yxInfoLists = getList(yxAccountInfo);
        for (int i = 0; i < yxInfoLists.size(); i++) {
            YxPayInfo yxPayInfo = JSONObject.parseObject(yxInfoLists.get(i).toString(), YxPayInfo.class);
            String track = DataUtil.getPayTrack(yxAccountInfo,yxPayInfo.getPayOrderCode() );
            YxPayTrack yxPayTrack = getYxPayTrack(track, yxPayInfo.getPayOrderCode());
            YxPayTrack payTrack = baseYxPayTrackService.findFirstByColumns(Columns.create("pay_order_code", yxPayInfo.getPayOrderCode()));
            if (payTrack == null) {
                baseYxPayTrackService.save(yxPayTrack);
            } else {
                baseYxPayTrackService.update(yxPayTrack);
            }
        }
    }

    /**
     * 获取一个YxDetails写入数据库
     *
     * @param detils
     * @param yxDetail
     * @return
     */
    public YxDetails getYxDetails(Detils detils, YxDetails yxDetail) {
        if (detils.getDisInfo().getResourceArea().equals("1")) {
            detils.getDisInfo().setResourceArea("进口");
        } else {
            detils.getDisInfo().setResourceArea("国产");
        }
        //结算数量
        yxDetail.setWarehouseCount(detils.getDisInfo().getWarehouseCount());
        //品牌
        yxDetail.setBrand(detils.getDisInfo().getBrand());
        //投标企业
        yxDetail.setCompanyName(detils.getDisInfo().getCompanyNameTb());
        //单位
        yxDetail.setUnit(detils.getDisInfo().getUnit());
        //分类/一级目录/二级目录/产地
        yxDetail.setProduceInfo(detils.getDisInfo().getSortName() + "/" + detils.getDisInfo().getProductNameFirst()
                + "/" + detils.getDisInfo().getProductNameSecond() + "/" + detils.getDisInfo().getResourceArea());
        //产品名称/注册证号
        yxDetail.setNameCode(detils.getDisInfo().getGoodsName() + "/" + detils.getDisInfo().getRegCode());
        return yxDetail;
    }

    /**
     * 返回一个YxPayTrack对象写入数据库
     *
     * @param track
     * @param orderNo
     * @return
     */
    public YxPayTrack getYxPayTrack(String track, String orderNo) {
        YxPayTrack yxPayTrack = new YxPayTrack();
        String[] str = new String[8];
        int j = 0;
        for (int i = 0; i < track.length(); i++) {
            if (track.charAt(i) >= '0' && track.charAt(i) <= '9') {
                str[j] = track.substring(i, i + 16);
                j++;
                i += 16;
            }
        }
        yxPayTrack.setT1(str[0]);
        yxPayTrack.setT2(str[1]);
        yxPayTrack.setT3(str[2]);
        yxPayTrack.setT4(str[3]);
        yxPayTrack.setT5(str[4]);
        yxPayTrack.setT6(str[5]);
        yxPayTrack.setT7(str[6]);
        yxPayTrack.setT8(str[7]);
        yxPayTrack.setPayOrderCode(orderNo);
        return yxPayTrack;
    }

    /**
     * 返回一个YxOrderDetails对象
     *
     * @param body
     * @param orderNo
     * @return
     */
    public YxOrderDetails getYxDetails(String body, String orderNo, YxAccountInfo yxAccountInfo) {
        YxOrderDetails yxOrderDetails = new YxOrderDetails();
        yxOrderDetails.setOrderName(StringUtils.substringBetween(body, "订单名称：", "</span>"));
        yxOrderDetails.setHarvestAmount(StringUtils.substringBetween(body, "收货明细总金额为", "元。"));
        yxOrderDetails.setReturnAmount(StringUtils.substringBetween(body, "退货明细总金额为", "元。"));
        yxOrderDetails.setAtatementAmount(StringUtils.substringBetween(body, "本订单结算的总金额为：", "元。"));

        StringBuilder sb = new StringBuilder();
        Document doc = Jsoup.parse(body);
        Elements eles1 = doc.select("label.control-label");
        for (int i = 0; i < eles1.size(); i++) {
            sb.append("\n").append(eles1.get(i).text());
        }
        String str = sb.toString();
        /**
         * 赋值
         */
        yxOrderDetails.setPaymentCompany(DataUtil.getRightStr(StringUtils.substringBetween(str, "付款单位：", "收款单位：").toString()));
        yxOrderDetails.setReceivingCompany(DataUtil.getRightStr(StringUtils.substringBetween(str, "收款单位：", "付款账号：")));
        yxOrderDetails.setPaymentAccount(DataUtil.getRightStr(StringUtils.substringBetween(str, "付款账号：", "收款账号：")));
        yxOrderDetails.setReceivingAccount(DataUtil.getRightStr(StringUtils.substringBetween(str, "收款账号：", "付款账号开户行联行号：")));
        yxOrderDetails.setPaymentUnionBankNum(DataUtil.getRightStr(StringUtils.substringBetween(str, "付款账号开户行联行号：", "收款账号开户行联行号")));
        yxOrderDetails.setReceivinhUnionBankNum(DataUtil.getRightStr(StringUtils.substringBetween(str, "收款账号开户行联行号：", "付款账号开户行名称：")));
        yxOrderDetails.setPaymentBankName(DataUtil.getRightStr(StringUtils.substringBetween(str, "付款账号开户行名称：", "收款账号开户行名称：")));
        yxOrderDetails.setReceivingBankName(DataUtil.getRightStr(StringUtils.substringBetween(str, "收款账号开户行名称：", "贷款账号：")));
        yxOrderDetails.setLoanAccount(DataUtil.getRightStr(StringUtils.substringBetween(str, "贷款账号：", "贷款账号户名：")));
        //有问题
        yxOrderDetails.setLoanAccountName(DataUtil.getRightStr(StringUtils.substringBetween(str, "贷款账号户名：","")));

        yxOrderDetails.setDatePulltime(new Date());
        yxOrderDetails.setDatePulluser(yxAccountInfo.getAccountUsername());
        yxOrderDetails.setPayOrderCode(orderNo);
        return yxOrderDetails;
    }
//  获取订单列表
    public JSONArray getList(YxAccountInfo yxAccountInfo) {
        LoginUtil.loginByPwd(yxAccountInfo);
        JSONArray payInfoList = DataUtil.getPayInfoList(yxAccountInfo);
        return payInfoList;
    }
}


